<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\18 0018
 * Time: 15:10
 */

namespace app\Lib\Model\HandleLog;


use app\Lib\Exception\SysException;
use app\Lib\InterfaceIn\HandleLog\AddHandleLogHandle;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\DbModel\HandleLogs;

class AddHandleLog implements AddHandleLogHandle
{
    private $opUser;
    private $content;
    private $type;
    private $obj;
    private $ip;
    public function __construct(UserHandle $opUser)
    {
        $this->opUser = $opUser;
    }

    /**
     * 操作内容
     * @param $content
     * @return $this
     */
    public function setContent($content)
    {
        $this->content = $content;
        return $this;
    }

    /**
     * 操作类型
     * @param $type
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * 操作对象
     * @param $obj
     * @return $this
     */
    public function setObj($obj)
    {
        $this->obj = $obj;
        return $this;
    }

    /**
     * 设置ip
     * @param $Ip
     * @return $this
     */
    public function setIp($Ip)
    {
        $this->ip = $Ip;
        return $this;
    }

    /**
     * 检验参数
     * @throws SysException
     */
    private function check(){
        if(empty($this->content)){
            throw new SysException('操作日志内容不能为空');
        }
        if(empty($this->obj)){
            throw new SysException('操作日志对象不能为空');
        }
        if(empty($this->type)){
            throw new SysException('操作日志类型不能为空');
        }
        if(empty($this->ip)){
            throw new SysException('操作日志Ip不能为空');
        }
        if($this->opUser instanceof UserHandle){
            throw new SysException('操作人对象错误');
        }
    }

    /**
     * 执行
     * @return bool
     * @throws SysException
     * @throws \think\Exception
     */
    public function run()
    {
        $this->check();
        $model = new HandleLogs();
        if(!get_transTimes())throw new SysException('必须开启事务');
        $data= [
            $model->_content=>$this->content,
            $model->_time=>time(),
            $model->_uid=>$this->opUser->getUid(),
            $model->_type=>$this->type,
            $model->_obj=>$this->obj,
            $model->_ip=>$this->ip
        ];
        $result = $model->insert($data);
        if(!$result){
            throw new SysException('日志记录失败');
        }
        return true;
    }

}